import { categoryDeviceApi } from '../../utils/category-device'
export default {
    name: 'furniture',
    data() {
        return {
            isEditing: false,
            categories: [],
            deviceList: [],
            debugInfo: ''
        }
    },

    methods: {
        // 获取设备图标（保持原有逻辑）
        getDeviceIcon(type) {
            const icons = {
                'light': '/static/灯光.png',
                'tempHumidity': '/static/温湿度.png',
                'air': '/static/空气质量.png',
                'smoke': '/static/烟雾浓度.png',
                'buzzer': '/static/蜂鸣器.png',
                'temp': '/static/温度.png',
                'humidity': '/static/湿度.png',
                '灯光': '/static/灯光.png',
                '温湿度': '/static/温湿度.png',
                '空气质量': '/static/空气质量.png',
                '烟雾浓度': '/static/烟雾浓度.png',
                '蜂鸣器': '/static/蜂鸣器.png',
                '光照强度': '/static/光照强度.png'
            }
            return icons[type] || '/static/灯光.png'
        },

        // 初始化分类和设备数据
        async initializeCategoriesAndDevices() {
            try {
                const [categoryResponse, deviceResponse] = await Promise.all([
                    categoryDeviceApi.getCategoryList(),
                    categoryDeviceApi.getDeviceList()
                ])

                if (
                    categoryResponse.statusCode === 200 &&
                    deviceResponse.statusCode === 200 &&
                    categoryResponse.data.code === 200 &&
                    deviceResponse.data.code === 200
                ) {
                    const categories = categoryResponse.data.data
                    const devices = deviceResponse.data.data

                    const categoriesWithDevices = categories.map(category => ({
                        name: category.categoryName,
                        id: category.id,
                        devices: devices
                            .filter(device => device.categoryId === category.id)
                            .map(device => ({
                                ...device,
                                name: device.title,
                                originalDevice: device
                            }))
                    }))

                    this.categories = categoriesWithDevices
                    this.deviceList = devices

                    console.log('初始化分类和设备:', this.categories)
                } else {
                    uni.showToast({
                        title: '获取数据失败',
                        icon: 'none'
                    })
                }
            } catch (error) {
                console.error('初始化失败:', error)
                uni.showToast({
                    title: '网络错误',
                    icon: 'none'
                })
            }
        },

        // 切换编辑模式并保存更改
        async toggleEditMode() {
            if (this.isEditing) {
                // 保存分类和设备更改
                await this.saveCategories()
                await this.saveDevices()
            }
            this.isEditing = !this.isEditing
        },

        // 保存分类更改
        async saveCategories() {
            try {
                for (const category of this.categories) {
                    if (category.id != null && category.name != null) {
                        const categoryDTO = {
                            id: category.id,
                            categoryName: category.name
                        };

                        console.log('准备发送的分类数据:', categoryDTO);
                        console.log('JSON字符串:', JSON.stringify(categoryDTO));

                        const response = await uni.request({
                            url: 'http://127.0.0.1:7878/category',
                            method: 'PUT',
                            data: JSON.stringify(categoryDTO), // 手动序列化 JSON
                            header: {
                                'Content-Type': 'application/json'
                            }
                        });

                        console.log('请求响应:', response);
                    }
                }
            } catch (error) {
                console.error('保存分类失败:', error);
            }
        },


        // 保存设备更改
        async saveDevices() {
            try {
                console.log('正在执行 saveDevices...');
                const devicesToUpdate = this.categories.flatMap(category =>
                    category.devices.map(device => ({
                        id: device.id,
                        categoryId: category.id,
                    }))
                );

                console.log('最终发送的设备数据:', JSON.stringify(devicesToUpdate, null, 2));

                const response = await uni.request({
                    url: 'http://127.0.0.1:7878/device',
                    method: 'PUT',
                    data: devicesToUpdate,
                    header: { 'Content-Type': 'application/json' }
                });

                console.log('设备保存返回:', response);


                if (response.data.code === 200) {
                    uni.showToast({
                        title: '设备保存成功',
                        icon: 'success'
                    })
                } else {
                    uni.showToast({
                        title: '设备保存失败',
                        icon: 'none'
                    })
                }
            } catch (error) {
                console.error('保存设备失败:', error)
                uni.showToast({
                    title: '网络错误',
                    icon: 'none'
                })
            }
        },

        // 获取可移动的分类选项
        getCategoryOptions(currentIndex) {
            return this.categories
                .filter((_, index) => index !== currentIndex)
                .map(category => category.name)
        },

        // 移动设备到其他分类
        moveDevice(fromCategoryIndex, deviceIndex, toCategoryNameIndex) {
            const toCategoryName = this.getCategoryOptions(fromCategoryIndex)[toCategoryNameIndex]
            const toCategoryIndex = this.categories.findIndex(c => c.name === toCategoryName)

            if (toCategoryIndex === -1) return

            // 移动设备
            const device = this.categories[fromCategoryIndex].devices[deviceIndex]
            this.categories[fromCategoryIndex].devices.splice(deviceIndex, 1)
            this.categories[toCategoryIndex].devices.push({
                ...device,
                categoryId: this.categories[toCategoryIndex].id
            })
        }
    },

    onLoad() {
        this.initializeCategoriesAndDevices()
    },

    onShow() {
        // 再次尝试初始化
        this.initializeCategoriesAndDevices()
    }
}